//
//  RMMYouHuiQuanViewController.m
//  Romomo
//
//  Created by puman on 16/10/10.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMYouHuiQuanViewController.h"
#import "RMMYouHuiQuanTableViewCell.h"
#import "RMMDuiHuanYouHuiQuanView.h"

@interface RMMYouHuiQuanViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@end

@implementation RMMYouHuiQuanViewController
{
    RMMDuiHuanYouHuiQuanView *_youHuiView;
    UITableView *_tableView;
    NSMutableDictionary *_dataDic;
    NSMutableDictionary *_statusDic;
    UIButton *_bottomBut;
    NSInteger _index;
    UILabel *_label;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(245, 246, 247, 1);
    self.navigationItem.title = @"使用优惠券";
    [self addViews];
    [self getRequestData];
    // Do any additional setup after loading the view.
}
- (void)addViews{
    [self addRightItem];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 49)];
    view.backgroundColor = kWhiteColor;
    [self.view addSubview:view];
    
    _label = [[UILabel alloc] init];
    _label.frame = CGRectMake(15, 0, 200, view.height);
    _label.text = @"不使用优惠券";
    _label.font = kFont(16);
    _label.textColor = COLORFROMCODE(0x4A4A4A, 1);
    [view addSubview:_label];
    
    _statusDic = [NSMutableDictionary dictionary];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64 - 49)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = NO;
    [_tableView registerClass:[RMMYouHuiQuanTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:_tableView];
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49 - 64, kScreenWideth, 49)];
    bottomView.backgroundColor = kWhiteColor;
    [self.view addSubview:bottomView];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, bottomView.width, 0.5)];
    lineLabel.backgroundColor = RGBA(221, 221, 221, 1);
    [bottomView addSubview:lineLabel];
    
    _bottomBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _bottomBut.frame = CGRectMake(kScreenWideth / 2 - kHalf * 2, 6.5, 4 * kHalf, 36);
    _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
    [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
    _bottomBut.titleLabel.font = kBFont(14);
    _bottomBut.layer.masksToBounds = YES;
    _bottomBut.layer.cornerRadius = 18;
    [_bottomBut setTitle:@"完成" forState:(UIControlStateNormal)];
    _bottomBut.userInteractionEnabled = NO;
    BUTTON_S(_bottomBut, nextButClick);
    [bottomView addSubview:_bottomBut];
    
    _youHuiView = [[RMMDuiHuanYouHuiQuanView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 64, kScreenWideth, kScreenHeight - 64)];
    _youHuiView.textF.delegate = self;
    TEXTFIELD_S(_youHuiView.textF, textFValueChanged:);
    BUTTON_S(_youHuiView.confirmBut, confimButExchange);
    BUTTON_S(_youHuiView.cancelBut, cancel);

    [self.view addSubview:_youHuiView];
}
- (void)textFValueChanged:(UITextField *)textF{
    if (textF.text.length) {
        [RMMFileManager butOnWithBut:_youHuiView.confirmBut];
    } else {
        [RMMFileManager butOffWithBut:_youHuiView.confirmBut];
    }
}
- (void)confimButExchange{
    [_youHuiView.textF resignFirstResponder];
    [UIView animateWithDuration:0.2 animations:^{
        _youHuiView.frame = CGRectMake(0, kScreenHeight - 64, kScreenWideth, kScreenHeight - 64);
    } completion:^(BOOL finished) {
        if (self.view.top != 64) {
            [UIView animateWithDuration:0.1 animations:^{
                self.view.frame = CGRectMake(0, 64, kScreenWideth, kScreenHeight);
            } completion:^(BOOL finished) {
                
            }];
        }
    }];
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"cust_id"] = [RMMFileManager shareHandle].userDic[@"cust_id"];
    parDic[@"coupon_no"] = _youHuiView.textF.text;
    [OSRequestManager requestWithUrlString:GetCouponUrl parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _youHuiView.textF.text = @"";
            [RMMFileManager butOnWithBut:_youHuiView.confirmBut];
            [MMProgressHUD show];
            [MMProgressHUD dismissWithSuccess:@"添加成功!" title:nil afterDelay:1.0];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self getRequestData];
            });
        } else {
            _youHuiView.textF.text = @"";
            [RMMFileManager butOnWithBut:_youHuiView.confirmBut];
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        _youHuiView.textF.text = @"";
        [RMMFileManager butOnWithBut:_youHuiView.confirmBut];
    } view:self.view];
}
- (void)cancel{
    [_youHuiView.textF resignFirstResponder];
    [UIView animateWithDuration:0.2 animations:^{
        _youHuiView.frame = CGRectMake(0, kScreenHeight - 64, kScreenWideth, kScreenHeight - 64);
    } completion:^(BOOL finished) {
        if (self.view.top != 64) {
            [UIView animateWithDuration:0.1 animations:^{
                self.view.frame = CGRectMake(0, 64, kScreenWideth, kScreenHeight);
            } completion:^(BOOL finished) {
                
            }];
        }
    }];
}
- (void)nextButClick{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)getRequestData{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate:date];
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = cust_id;
    NSString *url = GetCustVoucHerUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _dataDic = [NSMutableDictionary dictionary];
            NSArray *array = dataDic[@"data"][@"VoucherData"];
            NSInteger key = 0;
            for (NSDictionary *dic in array) {
                NSString *time = dic[@"DATE_PERIOD"];
                if ([time compare:dateString] == NSOrderedAscending) {
                    NSMutableArray *value = _dataDic[@"不可使用的优惠券"];
                    if (value == nil) {
                        value = [NSMutableArray array];
                        [_dataDic setObject:value forKey:@"不可使用的优惠券"];
                    }
                    [value addObject:[RMMFileManager setValueForDic:dic]];
                } else {
                    NSMutableArray *value = _dataDic[@"可使用的优惠券"];
                    if (value == nil) {
                        value = [NSMutableArray array];
                        [_dataDic setObject:value forKey:@"可使用的优惠券"];
                    }
                    [_statusDic setObject:@"0" forKey:[NSString stringWithFormat:@"%ld",key]];
                    [value addObject:[RMMFileManager setValueForDic:dic]];
                    key ++;
                }
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];
    } error:^(NSError *errors) {
        
    } view:self.view];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataDic.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array = [_dataDic allKeys];
    NSString *key = array[section];
    NSArray *value = _dataDic[key];
    return value.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 152;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = RGBA(245, 246, 247, 1);
    UILabel *label = [[UILabel alloc] init];
    [view addSubview:label];
    NSArray *array = [_dataDic allKeys];
    NSString *key = array[section];
    view.frame = CGRectMake(0, 0, kScreenWideth, 49);
    label.text = key;
    label.font = kFont(13);
    label.textColor = COLORFROMCODE(0x9B9B9B, 1);
    label.frame = CGRectMake(15, 0, 200, view.height);
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 49;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RMMYouHuiQuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    NSArray *array = [_dataDic allKeys];
    NSString *key = array[indexPath.section];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSMutableArray *value = _dataDic[key];
    cell.dic = value[indexPath.row];
    if ([key isEqualToString:@"可使用的优惠券"]) {
        cell.model = @"1";
        NSString *status = _statusDic[[NSString stringWithFormat:@"%ld",indexPath.row]];
        if ([status isEqualToString:@"1"]) {
            cell.selcetImageV.image= [UIImage imageNamed:@"优惠券-已选@3x"];
        } else {
            cell.selcetImageV.image= [UIImage imageNamed:@"优惠券可选@3x"];
        }
    } else {
        cell.model = @"0";
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _index = indexPath.row;
    NSString *status = _statusDic[[NSString stringWithFormat:@"%ld",indexPath.row]];
    for (int i = 0; i < [_statusDic allKeys].count; i++) {
        if (i == indexPath.row) {
            if ([status isEqualToString:@"0"]) {
                [_statusDic setObject:@"1" forKey:[NSString stringWithFormat:@"%d",i]];
            } else {
                [_statusDic setObject:@"0" forKey:[NSString stringWithFormat:@"%d",i]];
            }
        } else {
            [_statusDic setObject:@"0" forKey:[NSString stringWithFormat:@"%d",i]];
        }
    }
    NSArray *array = [_statusDic allValues];
    if ([array containsObject:@"1"]) {
        NSArray *value = _dataDic[@"可使用的优惠券"];
        NS_POST(@"USEYOUHUIQUAN", nil, value[_index]);
        _bottomBut.backgroundColor = kBasicColor;
        [_bottomBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
        _bottomBut.userInteractionEnabled = YES;
    } else {
        NS_POST(@"USEYOUHUIQUAN", nil, nil);
        _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
        [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
        _bottomBut.userInteractionEnabled = NO;
    }
    [_tableView reloadData];
}
- (void)addRightItem{
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"兑换优惠券" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightItemClick)];
    rightItem.tintColor = kBasicColor;
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)rightItemClick{
    if (_youHuiView.top == kScreenHeight - 64) {
        
        [UIView animateWithDuration:0.2 animations:^{
            _youHuiView.frame = CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64);
        } completion:^(BOOL finished) {
            if (kScreenWideth == 320) {
                [UIView animateWithDuration:0.1 animations:^{
                    self.view.frame = CGRectMake(0, 30, kScreenWideth, kScreenHeight);
                } completion:^(BOOL finished) {
                    
                }];
            }
        }];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [_youHuiView.textF resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
